import { create } from 'zustand'
import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'

export type State = {
  token: string,
  name: string,
  avatar: string,
  roles: string[],
  permissions: string[],
}

export type UserLogin = {
  username: string,
  password: string,
  code?: string,
  uuid?: string
}

type Action = {
  login: (userInfo: UserLogin) => Promise<{success: boolean}>
  getInfo: () => Promise<any>
  logOut: () => Promise<void>
}

const useUserStore = create<State & Action>((set, get) => ({
  token: getToken(),
  name: '',
  avatar: '',
  roles: [],
  permissions: [],
  async login(userInfo) {
    const { password, code, uuid } = userInfo
    const username = userInfo.username.trim()
    const {data, success} = await login(username, password, code, uuid)
    if(!success) return { success: false }
    setToken(data.token)
    set(() => ({ token: data.token }))
    return { success: true }
  },
  // 获取用户信息
  async getInfo() {
    const {data, success} = await getInfo()
    if(!success) return false
    const user = data.user
    const avatar = (user.avatar == "" || user.avatar == null) ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;
    // 验证返回的roles是否是一个非空数组
    if (data.roles && data.roles.length > 0) { 
      set(() => ({ roles: data.roles, permissions: data.permissions }))
    } else {
      set(() => ({ roles: ['ROLE_DEFAULT'] }))
    }
    set(() => ({ name: user.userName, avatar: avatar }))
    return data
  },
  // 退出系统
  async logOut() {
    await logout()
    set(() => ({ token: '', roles: [], permissions: []}))
    removeToken()
  }
}))


export default useUserStore